package com.example.wweather;

import android.app.Activity;
import android.os.Bundle;
import android.text.format.Time;
import android.util.Log;
import android.view.Menu;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import android.location.Location;
import android.location.LocationManager;
import android.content.Context;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;

public class Mapax extends Activity {
	private int userIcon = R.drawable.person;
	private int placesIcon = R.drawable.yellow_point;
	private int finn = R.drawable.red_point;

	private int bddIcon = R.drawable.impmarker;
	private int taxIcon = R.drawable.tax;

	private GoogleMap theMap;
	private LocationManager locMan;
	private Marker userMarker;
	ArrayList<Lugar> lugars;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mapax);
		if (theMap == null) {

			theMap = ((MapFragment) getFragmentManager().findFragmentById(
					R.id.the_map)).getMap();
			if (theMap != null) {
				theMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
				updatePlaces();

			
				
			}
		}

	}

	public boolean onMarkerClick(Marker marker) {

		return false;
	}

	private void updatePlaces() {
		locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		Location lastLoc = locMan
				.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
		double lat = lastLoc.getLatitude();
		double lng = lastLoc.getLongitude();
		LatLng lastLatLng = new LatLng(lat, lng);
		if (userMarker != null)
			userMarker.remove();
		userMarker = theMap.addMarker(new MarkerOptions().position(lastLatLng)
				.title("Yo")
				.icon(BitmapDescriptorFactory.fromResource(userIcon))
				.snippet("Te encuentras aqui"));
		theMap.animateCamera(CameraUpdateFactory.newLatLng(lastLatLng), 3000,
				null);

		// PLACES MARKERS
		String placesSearchStr = CreateUrl(lat, lng, 2000, "food%7Cbar");
		GetPlaces cercanos;
		cercanos = new GetPlaces();
		cercanos.doInBackground(placesSearchStr);
		PlaceHandler Parser = new PlaceHandler();
		JSONObject jObj = null;
		try {
			jObj = new JSONObject(cercanos.doInBackground(placesSearchStr));
		} catch (JSONException e) {
			Log.e("JSON Parser", "Error parsing data " + e.toString());
			e.printStackTrace();
		}
		Parser.startParsing(jObj);
		lugars = Parser.getPlaces();
		System.out.println(lugars.toString() + placesSearchStr);


/*
		ArrayList<Marker> markersP = new ArrayList<Marker>();

		for (int i = 0; i < lugars.size(); i++) {
			LatLng lalo = new LatLng(lugars.get(i).getLat(), lugars.get(i)
					.getLon());

			Marker mark = theMap.addMarker(new MarkerOptions().position(lalo)
					.title(lugars.get(i).getNombre())
					.icon(BitmapDescriptorFactory.fromResource(placesIcon))
					.snippet("\n" + lugars.get(i).getTipo().toString()));
			markersP.add(mark);
		}

		// BDD MARKERS
		misLugares misL = new misLugares();
		ArrayList<Marker> markersbdd = new ArrayList<Marker>();
		ArrayList<Lugar> locals = misL.bLugar();
		for (int i = 0; i < locals.size(); i++) {
			LatLng lalo = new LatLng(locals.get(i).getLat(), locals.get(i)
					.getLon());

			Marker mark = theMap.addMarker(new MarkerOptions().position(lalo)
					.title(locals.get(i).getNombre())
					.icon(BitmapDescriptorFactory.fromResource(bddIcon))
					.snippet("\n" + locals.get(i).getTipo().toString()));
			markersbdd.add(mark);
		}
*/
		// TAXIS

		String placesTax = CreateUrl(lat, lng, 2000, "taxi_stand");
		GetPlaces taxis;
		PlaceHandler Parsert = new PlaceHandler();

		taxis = new GetPlaces();

		taxis.doInBackground(placesSearchStr);
		JSONObject jObjTax = null;
		try {
			jObjTax = new JSONObject(taxis.doInBackground(placesTax));
		} catch (JSONException e) {
			Log.e("JSON Parser", "Error parsing data " + e.toString());
			e.printStackTrace();
		}
		Parsert.startParsing(jObjTax);
		ArrayList<Lugar> taxs;
		taxs = Parsert.getPlaces();
		ArrayList<Marker> markerst = new ArrayList<Marker>();

		for (int i = 0; i < taxs.size(); i++) {
			LatLng lalo = new LatLng(taxs.get(i).getLat(), taxs.get(i).getLon());

			Marker mark = theMap.addMarker(new MarkerOptions().position(lalo)
					.title(taxs.get(i).getNombre())
					.icon(BitmapDescriptorFactory.fromResource(taxIcon))
					.snippet("\n" + taxs.get(i).getTipo().toString()));
			markerst.add(mark);
		}
		AgSugLug agnt = new AgSugLug();
		Bundle extras = getIntent().getExtras();
		
		ArrayList<String> gustos = new ArrayList<String> ();

		int califs[] = extras.getIntArray("Califs");
		String sexo = extras.getString("Sexo");
		String medio = extras.getString("Medio");
		String ocup = extras.getString("Ocup");
		String acomp = extras.getString("Acomp");
		int pres = extras.getInt("Pres");
		int[] gust = extras.getIntArray("Gustos");
		int edad = extras.getInt("Edad");
		int clima = extras.getInt("CodClima");
		int temp = extras.getInt("TempAc");

		for (int i=0;i<gust.length;i++){
			if(gust[0]==2){
				gustos.add("Picante");
			}
			else if(gust[1]==2){
				gustos.add("Dulce");
			}else if(gust[2]==2){
				gustos.add("Agridulce");
			}else if(gust[3]==2){
				gustos.add("Salado");
			}
			
		}
		String mitipo= agnt.getTipo( califs, edad, temp, gustos, ocup,acomp,pres);
		int rad =agnt.radio(clima, medio);
		ArrayList<Lugar> res = new ArrayList<Lugar>();
		res = agnt.getbyType(mitipo);
		for (int i = 0; i < res.size(); i++) {
			System.out.println(res.get(i).getNombre());
		}
		res = agnt.getbyRadio(res, rad, lat, lng);
		for (int i = 0; i < res.size(); i++) {
			System.out.println(res.get(i).getNombre());
		}
		Lugar fin = new Lugar();
		fin= agnt.lResult(res);
		System.out.println("Lugar "+fin);
		LatLng llola = new LatLng(fin.getLat(), fin.getLon());
		Marker mark = theMap.addMarker(new MarkerOptions().position(llola)
				.title(fin.getNombre())
				.icon(BitmapDescriptorFactory.fromResource(finn))
				.snippet("\n" + fin.getTipo().toString()));
	/*	ArrayList<Marker> markersrec = new ArrayList<Marker>();
		for (int i = 0; i < res.size(); i++) {
			LatLng lalo = new LatLng(res.get(i).getLat(), res.get(i)
					.getLon());

			Marker mark = theMap.addMarker(new MarkerOptions().position(lalo)
					.title(res.get(i).getNombre())
					.icon(BitmapDescriptorFactory.fromResource(userIcon))
					.snippet("\n" + res.get(i).getTipo().toString()));
			markersrec.add(mark);
		}*/
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main_activity, menu);
		return true;
	}

	public String CreateUrl(Double lat, Double lon, int radio, String query) {
		String placesSearchStr = "https://maps.googleapis.com/maps/api/place/nearbysearch/"
				+ "json?location="
				+ lat
				+ ","
				+ lon
				+ "&radius="
				+ radio
				+ "&sensor=true&types="
				+ query
				+ "&key=AIzaSyAWm_EshLdnwL08HZMzAsvwF0aIneoSRhs";
		return placesSearchStr;
	}


	private class GetPlaces extends AsyncTask<String, Void, String> {

		@Override
		protected String doInBackground(String... placesURL) {
			StringBuilder placesBuilder = new StringBuilder();
			// process search parameter string(s)
			for (String placeSearchURL : placesURL) {
				HttpClient placesClient = new DefaultHttpClient();
				try {
					HttpGet placesGet = new HttpGet(placeSearchURL);
					HttpResponse placesResponse = placesClient
							.execute(placesGet);
					// check response status
					StatusLine placeSearchStatus = placesResponse
							.getStatusLine();
					// only carry on if response is OK
					if (placeSearchStatus.getStatusCode() == 200) {
						// get response entity
						HttpEntity placesEntity = placesResponse.getEntity();
						// get input stream setup
						InputStream placesContent = placesEntity.getContent();
						// create reader
						InputStreamReader placesInput = new InputStreamReader(
								placesContent);
						// use buffered reader to process
						BufferedReader placesReader = new BufferedReader(
								placesInput);
						// read a line at a time, append to string builder
						String lineIn;
						while ((lineIn = placesReader.readLine()) != null) {
							placesBuilder.append(lineIn);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
			return placesBuilder.toString();
		}

	}
}
